package com.example.jdcompetition.Controller;

import com.alibaba.fastjson.JSONObject;
import com.example.jdcompetition.Entity.CodeAndMsg;
import com.example.jdcompetition.Service.cvsPro.jd.Solution;
import com.example.jdcompetition.Entity.OnePieceIno;
import com.example.jdcompetition.Entity.CallResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import static com.example.jdcompetition.JdcompetitionApplication.*;

/**
 * @author henrydai
 * @date 2021/6/16 11:23
 */

@RestController
@Slf4j
public class InquiryController {

    @Autowired
    private UniformReponseHandler<String> uniformReponseHandler;
    @Autowired
    private Solution solution;

    @GetMapping(value = "/inquiry",produces = "application/json")
//    public String inquiry(@RequestParam("orderTime")String orderTime,
//                          @RequestParam("oriPro")String oriPro, @RequestParam("oriCity")String oriCity,
//                          @RequestParam("oriDist")String oriDist, @RequestParam("oriVill")String oriVill,
//                          @RequestParam("desPro")String desPro, @RequestParam("desCity")String desCity,
//                          @RequestParam("desDist")String desDist,@RequestParam("desVill")String desVill)
    public CallResultMsg inquiry(@RequestBody JSONObject jsonParams)
    {
        long start = System.nanoTime();
        OnePieceIno opi = new OnePieceIno(jsonParams.getString("orderTime"),
                jsonParams.getString("oriPro"), jsonParams.getString("oriCity"),
                jsonParams.getString("oriDist"), jsonParams.getString("oriVill"),
                jsonParams.getString("desPro"), jsonParams.getString("desCity"),
                jsonParams.getString("desDist"), jsonParams.getString("desVill"));
        CallResultMsg<OnePieceIno> crm = new CallResultMsg<OnePieceIno>(true, CodeAndMsg.SUCCESS,opi);
        //考虑HashMap不支持多线程
        if(isPrepared)
        {
            //执行配送时效查询
            CallResultMsg<String> crs = solution.inqury(opi);
            //根据查询结果选择响应数据类型
            if(crs.getCode()==CodeAndMsg.SUCCESS.getCode())
            {
                crm.getData().setArriveTime(crs.getData());
                logWarn(start);
                return crm;
            }
            else
            {
                logWarn(start);
                return crs;
            }

        }
        else
        {
            logWarn(start);
            return uniformReponseHandler.unkownException("数据文件尚未处理完毕,攒不提供查询服务,请先调用处理文件API:'localhost:8080/henry/savedata'");
        }
    }

    //记录本次处理后台处理时间
    private void logWarn(long start)
    {
        long temp = System.nanoTime()-start;
        log.warn("本次查询处理时间:"+temp+"ns");
    }
}
